import React, { Component } from 'react';
import Dialog from 'material-ui/Dialog';
import FontIcon from 'material-ui/FontIcon';
import TextField from 'material-ui/TextField';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton';
import CircularProgress from 'material-ui/CircularProgress';
import CONFIG from '../../config';
import { parseJSON, getMethod, postJsonMethod } from '../../redux/Helper';

/**
 * 计算字数
 */
function sumText(str) {
  var len = 0;
  for (var i=0; i<str.length; i++) {    
    if (str.charCodeAt(i)>127 || str.charCodeAt(i)==94) {    
      len += 2;  
    }else{
      len ++;  
    }
  }
  return len;
}

export default class Tweet extends Component {
  initState = {
    userId: null,
    source: null,
    share: null,
    detail: '',
    sumDetail: 240,
    fileName: null,
    isPost: false
  };

  constructor(props) {
    super(props);
    this.state = this.initState;
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      userId: nextProps.userId,
      source: nextProps.activityId,
    });
  }

  /**
   * 关闭
   */
  close = () => {
    this.setState(this.initState);
    this.props.handleClose();
  };

  /**
   * 发布
   */
  submit = () => {
    var data = new FormData();
    data.append('share', this.state.share);
    data.append('user_id', this.state.userId);
    data.append('source', this.state.source);
    data.append('detail', this.state.detail);

    if (!this.state.share && this.state.detail == '') {
      this.close();
    }else{
      let url = CONFIG.apiHost + '/api/tweet?token=' + this.props.token;

      this.setState({isPost: true});
      fetch(url, {
        method: 'post',
        body: data
      })
      .then(res => {
        if (res.ok) {
          this.props.handleOpenSnackbar('分享成功！');
          this.close();
        }
      })
      .catch(e => {
        // console.log(e);
        // 错误处理
      })
    }
  };

  /**
   * 修改state
   */
  handleChange = (e) => {
    let str = e.target.value;
    let len = sumText(str);
    if (len <= 240) {
      let v = 240 - len;
      this.setState({
        detail: str,
        sumDetail: v
      });
    }else{
      e.target.value = this.state.detail;
    }
  };

  /**
   * 处理上传图片
   */
  handleUploadImage = (e) => {
    let file = e.target.files[0];
    // let src = window.URL.createObjectURL(file);
    this.setState({
      fileName: file.name,
      share: file
    });
  };

  render() {
    let actions = (
      <div>
        {this.state.isPost ? 
          <CircularProgress 
            style={{margin: 6, marginLeft: 32, marginRight: 32}}
            size={24}
          /> : 
          <FlatButton
            label="分享"
            labelPosition="before"
            primary={true}
            onTouchTap={this.submit}
            icon={<FontIcon className="icon-send" />}
          />
        }
      </div>
    );

    let uploadContent = (
      <div style={styles.upload}>
        <span style={styles.span}>{this.state.fileName}</span>
        <FlatButton
          style={styles.btn}
          label="选择相片"
          labelPosition="before"
          containerElement="label"
        >
          <input 
            type="file" 
            className="upload-file"
            onChange={this.handleUploadImage}
            accept="image/png, image/gif, image/jpg, image/jpeg"
          />
        </FlatButton>
      </div>
    );

    let content = (
      <div style={styles.content}>
        <TextField
          floatingLabelText='活动都发生了什么有趣事？'
          multiLine={true}
          rows={4}
          fullWidth={true}
          onChange={this.handleChange}
        />
        <span>{this.state.sumDetail}</span>
      </div>
    );

  	return (
  	  <Dialog
        actions={actions}
        modal={false}
        open={this.props.open}
        onRequestClose={this.close}
        contentStyle={{
          width: this.props.isSmallViewport ? '100%' : 560, 
          position: 'relative'
        }}
        bodyStyle={{padding: 0}}
        overlayStyle={{backgroundColor: 'rgba(0,0,0,0.12)'}}
      >
        {uploadContent}
        
        {content}
      </Dialog>
  	);
  }
};

const styles = {
  upload: {
    position: 'relative',
    padding: 0,
    height: 72,
    borderBottomWidth: 1,
    borderBottomColor: 'rgb(224, 224, 224)',
    borderBottomStyle: 'solid',
  },
  content: {
    padding: 24,
    paddingTop: 0,
  },
  btn: {
    position: 'absolute',
    bottom: 18,
    right: 12
  },
  span: {
    position: 'absolute',
    bottom: 26,
    left: 24
  }
}